import * as Koa from 'koa';
import { Transaction } from 'tiny-entity2';
import { Guid, route, RouteOptionsVerify, ServiceManager } from "../../common";
import { ServiceException } from '../../common/excpetion';
import { ApiDataContext } from '../../domain/apiDataContext';
import { AccountPermits } from '../../domain/models/accountPermits';
import { AccountPermitsService } from '../../service/AccountPermitsService';
const actPermitsSvr = ServiceManager.Current.GetService<AccountPermitsService>('AccountPermitsService');

class AccountPermitsController {
    @route(new RouteOptionsVerify('GET', '/api/accountpermits'))
    async queryAccountPermitss(ctx: Koa.Context, next) {
        let params = ctx.query;
        let data = await actPermitsSvr.QueryAccountPermits(params);
        ctx.response.body = data;
        await next();
    }
   
    @route(new RouteOptionsVerify('POST', '/api/accountpermits'))
    async createAccountPermits(ctx: Koa.Context, next) {
        let permits: AccountPermits[] = ctx.request.body;
        let permitsResult: AccountPermits[] = <AccountPermits[]>{};

        if (!permits || permits.length <= 0) {
            throw new ServiceException("添加的权限不能为空", "not_be_null");
        }
        let delPara: AccountPermits = <AccountPermits>{ authObjectId: permits[0].authObjectId, authObjectType: permits[0].authObjectType };

        await Transaction(new ApiDataContext(), async datactx => {
            await actPermitsSvr.DeleteAccountPermits(delPara,datactx);

            for (let i = 0; i < permits.length; i++) {
                permits[i].id = Guid.GetGuid();
                let result = await actPermitsSvr.CreateAccountPermits(permits[i], datactx);
              //  permitsResult.fill(result);

            }
        });
        ctx.response.body = permits;
        await next();
    }
    // @route(new RouteOptionsVerify('PUT', '/api/accountpermits'))
    // async updateAccountPermits(ctx: Koa.Context, next) {
    //     ctx.response.body = null;
    //     await next();
    // }
    @route(new RouteOptionsVerify('DELETE', '/api/accountpermits'))
    async deleteAccountPermits(ctx: Koa.Context, next) {
        let params = ctx.query;
        let data = await actPermitsSvr.DeleteAccountPermits(params);
        ctx.response.body = data;
        await next();
    }
}